// ignore_for_file: use_build_context_synchronously

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/controller/user_info_controller.dart';
import 'package:flutter_house_manager/pages/Location/CameraDialog.dart';

import 'package:flutter_house_manager/utils/toast.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 1. 从GetX中获取用户信息控制器
  UserInfoController controller = Get.find<UserInfoController>();

  // 输入框控制器
  TextEditingController nicknameController = TextEditingController();

  // 临时存储头像图片地址和名称
  String tempAvatar = '';
  String tempFileName = '';

  /// 保存用户信息
  saveUserInfo() async {
    // 1. 获取用户输入的昵称
    String nickName = nicknameController.text;

    // 2. 内容校验
    // 2.1 昵称不能为空
    if (nickName.isEmpty) {
      PromptAction.showWarning('昵称不能为空');
      return;
    }
    // 2.2 昵称只能输入中文, 长度在2-10个字符之间
    if (!RegExp(r'^[\u4e00-\u9fa5]{2,10}$').hasMatch(nickName)) {
      PromptAction.showWarning('昵称只能输入中文');
      return;
    }

    //--------------------------------------
    String avatar = controller.userInfo['avatar'] ?? '';
    if (tempAvatar.isNotEmpty) {
      FormData data;
      // 如果是网页端
      if (kIsWeb) {
        // 1. 根据图片的临时路径得到二级制文件
        Uint8List list = await XFile(tempAvatar).readAsBytes();
        // 2. 获取文件对象
        MultipartFile file = MultipartFile.fromBytes(
          list,
          filename: tempFileName,
        );
        // 3. 创建FormData对象
        data = FormData.fromMap({"file": file, "type": "avatar"});
      } else {
        // 如果是其它移动端(鸿蒙, 安卓, iOS)
        data = FormData.fromMap(
            {"file": MultipartFile.fromFileSync(tempAvatar), "type": "avatar"});
      }

      // 4. 调用接口
      final res = await uploadAvatarAPI(data);
      avatar = res['url'];
    }
    //--------------------------------------

    // 3. 调用接口
    await updateUserInfoAPI({'nickName': nickName, 'avatar': avatar});

    tempAvatar = '';
    tempFileName = '';

    // 4. 提示保存成功
    PromptAction.showSuccess('保存成功');
    // 5. 同步Getx数据
    controller.userInfo['nickName'] = nickName;
    controller.userInfo['avatar'] = avatar;
    controller.update();
    // 6. 返回
    Navigator.of(context).pop();
  }

  /// 打开相册获取图片
  openLibrary() async {
    // 1. 创建一个选择图片的实例
    ImagePicker picker = ImagePicker();
    // 2. 调用方法打开相册
    // ImageSource.gallery 获取相册图片
    // ImageSource.camera 获取相机图片
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    // 3. 判断图片是否获取成功
    if (file != null) {
      // PromptAction.showSuccess('获取相册图片成功');
      // PromptAction.showSuccess(file.path);

      // 4. 存储图片地址和名称
      tempAvatar = file.path;
      tempFileName = file.name;
      // 5. 刷新UI
      setState(() {});

      Navigator.of(context).pop();
    }
  }

  /// 拍照
  openCamera() async {
    // 1. 创建一个选择图片的实例
    ImagePicker picker = ImagePicker();
    // 2. 调用方法打开相册
    // ImageSource.gallery 获取相册图片
    // ImageSource.camera 获取相机图片
    XFile? file = await picker.pickImage(source: ImageSource.camera);
    // 3. 判断图片是否获取成功
    if (file != null) {
      // PromptAction.showSuccess('获取相册图片成功');
      // PromptAction.showSuccess(file.path);

      // 4. 存储图片地址和名称
      tempAvatar = file.path;
      tempFileName = file.name;
      // 5. 刷新UI
      setState(() {});

      Navigator.of(context).pop();
    }
  }

  @override
  void initState() {
    super.initState();
    // 初始化输入框控制器
    nicknameController.text = controller.userInfo['nickName'] ?? '';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        // showSheet();
                        showCameraDialog(context, onLibrary: () {
                          openLibrary();
                        }, onCamera: () {
                          openCamera();
                        });
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getUserAvatar(),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: nicknameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  Widget getUserAvatar() {
    // 判断用户是否已经选择了头像
    if (tempAvatar.isNotEmpty) {
      // 判断是否是web端
      if (kIsWeb) {
        return Image.network(
          tempAvatar,
          width: 30,
          height: 30,
          fit: BoxFit.cover,
        );
      } else {
        // 移动端使用file文件显示图片
        return Image.file(
          File(tempAvatar),
          width: 30,
          height: 30,
          fit: BoxFit.cover,
        );
      }
    }

    if (controller.userInfo['avatar'] != '' &&
        controller.userInfo['avatar'] != null) {
      return Image.network(
        controller.userInfo['avatar'],
        width: 30,
        height: 30,
        fit: BoxFit.cover,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
      fit: BoxFit.cover,
    );
  }
}
